#ifndef CHATROOM_H
#define CHATROOM_H

#include <QWidget>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUdpSocket>
#include <QDataStream>
#include <QList>
#include <QHostAddress>
#include <QNetworkInterface>
#include <QTimer>
#include <QListWidget>
#include <QTime>
#include <QDebug>
QT_BEGIN_NAMESPACE
namespace Ui {
class Chatroom;
}
QT_END_NAMESPACE

class Chatroom : public QWidget
{
    Q_OBJECT

public:
    Chatroom(QString name, QWidget *parent = nullptr);
    ~Chatroom();

    enum Msgtype
    {
        sndmsg,
        user_enter,
        user_left,
        online_broadcast
    };

    class Userinfo
    {
    public:
        QString username;
        QString userIP;
        quint16 userport;
        QTime lastinfotime;
        Userinfo(QString name, QString IP,quint16 port) : username(name), userIP(IP), userport(port) {}

        // 重载 == 运算符
        bool operator==(const Userinfo &other) const {
            return (this->username == other.username) && (this->userIP == other.userIP) && (this->userport == other.userport);
        }
    };

    uint8_t sndMessage(Msgtype);//广播UDP消息
    void setName(QString);
    QString getName();
    QString getMsg();
    QString getIP();
    quint16 getPort();
    void recMessage(); //接收UDP消息
    void broadcastUserInfo(); //广播用户
    void onUserItemDoubleClicked(QListWidgetItem *item); // 添加双击事件的槽函数
private slots:
    void newConnection_Slot();
    void on_bt_yes_clicked();

private:
    Ui::Chatroom *ui;
    QTcpServer *tcpServer;
    QList<QTcpSocket *> clientSockets;
    QString uname;
    quint16 port;
    QUdpSocket *udpSocket;
    QString uIP;
    int online_users;
    QList<Userinfo> userlist;
    QTimer *broadcastTimer;
    QTimer *updatelistTimer;
    void updateUserList();
    void addUserToList(const Userinfo &user);
};
#endif // CHATROOM_H
